{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "raw_mimetype": "text/restructuredtext"
   },
   "source": [
    ".. _nb_binary:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Binary Variable Problem\n",
    "\n",
    "Mostly, *pymoo* was made for continuous problems, but of course, other variable types can be used as well. The genetic algorithm is a modular class. By modifying the sampling, crossover, and mutation (in some cases also repair), different kinds of variable types can be used (also more complicated ones such as tree, graph, ...)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the following the classical knapsack problem is considered. A single-objective genetic algorithm with a random initial population, half uniform binary crossover and a bitflip mutation is initialized."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "from pymoo.algorithms.soo.nonconvex.ga import GA\n",
    "from pymoo.operators.crossover.pntx import TwoPointCrossover\n",
    "from pymoo.operators.mutation.bitflip import BitflipMutation\n",
    "from pymoo.operators.sampling.rnd import BinaryRandomSampling\n",
    "from pymoo.optimize import minimize\n",
    "from pymoo.problems.single.knapsack import create_random_knapsack_problem\n",
    "\n",
    "problem = create_random_knapsack_problem(30)\n",
    "\n",
    "algorithm = GA(\n",
    "    pop_size=200,\n",
    "    sampling=BinaryRandomSampling(),\n",
    "    crossover=TwoPointCrossover(),\n",
    "    mutation=BitflipMutation(),\n",
    "    eliminate_duplicates=True)\n",
    "\n",
    "res = minimize(problem,\n",
    "               algorithm,\n",
    "               ('n_gen', 100),\n",
    "               verbose=False)\n",
    "\n",
    "print(\"Best solution found: %s\" % res.X.astype(int))\n",
    "print(\"Function value: %s\" % res.F)\n",
    "print(\"Constraint violation: %s\" % res.CV)\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
